package com.hpch.business.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hpch.business.mapper.ArticleMapper;
import com.hpch.business.service.ArticleService;
import com.hpch.business.entity.Article;
import com.hpch.business.param.ArticleParam;
import com.hpch.common.core.exception.BusinessException;
import com.hpch.common.core.utils.JSONUtil;
import com.hpch.common.core.web.PageParam;
import com.hpch.common.core.web.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 单页内容表Service实现
 *
 * @author EleAdmin
 * @since 2025-03-02 19:12:18
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Override
    public PageResult<Article> pageRel(ArticleParam param) {
        PageParam<Article, ArticleParam> page = new PageParam<>(param);
        page.setDefaultOrder("show_time desc");
        List<Article> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Article> listRel(ArticleParam param) {
        List<Article> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Article, ArticleParam> page = new PageParam<>();
        page.setDefaultOrder("show_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Article getByIdRel(Integer id) {
        ArticleParam param = new ArticleParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean edit(Article entity) {
        //
        Date showTime = entity.getShowTime();
        if (null == showTime){
            entity.setShowTime(new Date());
        }

        if (entity.getId() == null) {
            return save(entity);
        }
        updateById(entity);

        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean recommend(Article article) {
        // 根据id
        Article entity = getById(article.getId());
        if (entity == null) {
            throw new BusinessException("信息不存在");
        }

        Article update = new Article();
        update.setId(article.getId());
        update.setFlag(entity.getFlag()==1?0:1);
        if (StrUtil.isNotEmpty(article.getRecImg())){
            update.setRecImg(article.getRecImg());
        }
        return updateById(update);
    }


    public static void main(String[] args) {

        // 发起对话
        String chatUrl = "https://api.coze.cn/v3/chat";


        // 参数
        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("bot_id", "7480800297339011072");
        // user_id
        bodyMap.put("user_id", "123");

        // auto_save_history
        bodyMap.put("auto_save_history", true);
        // stream
        bodyMap.put("stream", true);


        // additional_messages
        List<Map<String, Object>> additional_messagesList = new ArrayList();


        Map<String, Object> additional_messages = new HashMap<>();
        /**
         * String
         * 必选
         * 发送这条消息的实体。取值：
         * user：代表该条消息内容是用户发送的。
         * assistant：代表该条消息内容是智能体发送的。
         */
        additional_messages.put("role", "user");
        additional_messages.put("content_type", "object_string");
//        additional_messages.put("content_type", "text");

        /**
         * 消息的内容，支持纯文本、多模态（文本、图片、文件混合输入）、卡片等多种类型的内容。
         * content_type 为 object_string 时，content 为 object_string object 数组序列化之后的 JSON String，详细说明可参考 object_string object。
         * 当 content_type = text 时，content 为普通文本，例如 "content" :"Hello!"。
         */

        List<Map<String, Object>> contentList = new ArrayList();
        Map<String, Object> content = new HashMap<>();
        content.put("type", "text");
        content.put("text", "你好,你是做什么的？");
        contentList.add(content);
        additional_messages.put("content", JSONUtil.toJSONString(contentList));


        additional_messagesList.add(additional_messages);
        bodyMap.put("additional_messages", additional_messagesList);
//        bodyMap.put("content", "你好,你是做什么的？");
        //
        System.out.println("bodyMap::::"+JSONUtil.toJSONString(bodyMap));


        // 使用 httpUtil
        //链式构建请求
        String result = HttpRequest.post(chatUrl)
                // Authorization Bearer $Access_Token
                .header(Header.AUTHORIZATION, "Bearer pat_h0MWo6ZvlQm7Jae7irsPf7Ear5O7gJKlspIOlTEDo8dlOvlapmmp4lPbuEq2qL2X")
//                .header(Header.AUTHORIZATION, "pat_h0MWo6ZvlQm7Jae7irsPf7Ear5O7gJKlspIOlTEDo8dlOvlapmmp4lPbuEq2qL2X")
                // Content-Type application/json
                .contentType("application/json")
                //头信息，多个头信息多次调用此方法即可
                .body(JSONUtil.toJSONString(bodyMap))//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();

        System.out.println("result::::"+result);

/*
        // 转成map
        Map<String, Object> resultMap = JSONUtil.parseObject(result, Map.class);


        Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");






        String conversation_id = Objects.toString(dataMap.get("conversation_id"),"");
        String chat_id = Objects.toString(dataMap.get("id"),"");

        // 查看对话详情
        String chatDetailUrl = "https://api.coze.cn/v3/chat/retrieve?chat_id=" + chat_id + "&conversation_id=" + conversation_id;


        // 参数
        Map<String, Object> chatDetailMap = new HashMap<>();
        chatDetailMap.put("chat_id", chat_id);
        chatDetailMap.put("conversation_id", conversation_id);

//        chatDetailMap.put("bot_id", "7480800297339011072");

        // 1s 调用一次
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        Runnable task = () -> {
            // 这里放置你想要每秒执行的操作
            System.out.println("执行一次操作 start : " + System.currentTimeMillis());
            // get 请求带 token
            String resultDetail = HttpRequest.get(chatDetailUrl)
                    // Authorization Bearer $Access_Token
                    .header(Header.AUTHORIZATION, "Bearer pat_h0MWo6ZvlQm7Jae7irsPf7Ear5O7gJKlspIOlTEDo8dlOvlapmmp4lPbuEq2qL2X")
                    .contentType("application/json")
                    .timeout(20000)
                    .execute().body();

            System.out.println("执行一次操作 end  :"+resultDetail);
            //  （status=completed） 跳出循环
            Map<String, Object> resultMapDetail = JSONUtil.parseObject(resultDetail, Map.class);
            Map<String, Object> dataMapDetail = (Map<String, Object>) resultMapDetail.get("data");
            String status = Objects.toString(dataMapDetail.get("status"),"");
            if ("completed".equals(status)){
                System.out.println("status::::"+status);
               // 跳出 task 继续执行下面的代码
                executor.shutdown();


                // 查看对话消息详情
                String chatDetailInfoUrl = "https://api.coze.cn/v3/chat/message/list?chat_id=" + chat_id + "&conversation_id=" + conversation_id;

                // get 请求带 token
                String resultDetailInfo = HttpRequest.get(chatDetailInfoUrl)
                        // Authorization Bearer $Access_Token
                        .header(Header.AUTHORIZATION, "Bearer pat_h0MWo6ZvlQm7Jae7irsPf7Ear5O7gJKlspIOlTEDo8dlOvlapmmp4lPbuEq2qL2X")
                        .contentType("application/json")
//                .form(chatDetailMap)
                        .timeout(20000)
                        .execute().body();

                System.out.println("resultDetailInfo::::"+resultDetailInfo);
            }

        };
        // 设置延迟0毫秒后开始执行，每1秒执行一次
        executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);


*/



    }

}
